package com.tutu.user.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.beanutils.BeanPredicate;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.PredicateUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tutu.common.GlobalConstants;
import com.tutu.common.GlobalConstants.ISessionMessageSetting;
import com.tutu.common.util.BeanUtils;
import com.tutu.common.util.DatatablesJson;
import com.tutu.common.util.JsonReturnObject;
import com.tutu.common.util.LogAction;
import com.tutu.common.util.MD5;
import com.tutu.common.util.SysAuditModelType;
import com.tutu.user.entity.SysMenuInfo;
import com.tutu.user.entity.SysUser;
import com.tutu.user.entity.SysUserGroup;
import com.tutu.user.entity.SysUserGroupMebers;
import com.tutu.user.entity.SysUserGroupPower;
import com.tutu.user.entity.vo.SysMenuInfoVO;
import com.tutu.user.entity.vo.SysUserGroupVO;
import com.tutu.user.service.ISysMenuInfoService;
import com.tutu.user.service.ISysUserGroupMebersService;
import com.tutu.user.service.ISysUserGroupPowerService;
import com.tutu.user.service.ISysUserGroupService;
import com.tutu.user.service.ISysUserService;

@Controller
@RequestMapping("/sysuser")
@LogAction(ownermodel=SysAuditModelType.SYSTEM_MANAGEMENT)
public class SysUserAction {

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private ISysUserService sysUserSerivce;
	@Resource
	private ISysUserGroupService sysUserGroupService;
	@Resource
	private ISysUserGroupMebersService sysUserGroupMebersService;
	@Resource
	private ISysMenuInfoService sysMenuInfoService;
	@Resource
	private ISysUserGroupPowerService sysUserGroupPowerService;
	
	@RequestMapping("/querySysUserPage")
	public String querySysUserPage(Model model){
		SysUser sysUser = new SysUser();
//		PageHelper.startPage(1, GlobalConstants.DEFAULT_PAGE_NUMBER);
		try{
			List<SysUser> sysUsers = sysUserSerivce.getUsers(sysUser);
			PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(sysUsers);
			pageInfo.setList(sysUsers);
			model.addAttribute("pageInfo", pageInfo);
		}catch(Exception e){
			logger.error("获取用户记录", e);
		}
		return "sysuser/querySysUserPage";
	}
	
	@RequestMapping("/createSysUser")
	public String createSysUser(){
		return "sysuser/createSysUser";
	}
	
	@RequestMapping("/saveSysUser")
	@LogAction(description="创建用户信息")
	public String saveSysUser(@ModelAttribute("sysUserFrom") SysUser sysUser){
		sysUser.setAliveFlag(GlobalConstants.FLAG_ENABLE);
		sysUser.setPassword(MD5.toMD5(GlobalConstants.DEFAULT_PASSWORD));
		if(null!=GlobalConstants.getCurrentUser())
			sysUser.setCreator(GlobalConstants.getCurrentUser().getUserId());
		else
			sysUser.setCreator(GlobalConstants.SYSTEM_USER);
		try{
			this.sysUserSerivce.saveUser(sysUser);
		}catch(Exception e){
			logger.error("创建用户信息", e);
		}
		return "redirect:/sysuser/querySysUserPage.do";
	}
	
	@RequestMapping("/existsLoginName")
	@ResponseBody
	public boolean existsLoginName(@RequestParam String loginName){
		return !this.sysUserSerivce.existsLoginName(loginName);
	}
	
	@RequestMapping("/getMyUser")
	public String getMyUser(Model model){
		getSysUser(model, GlobalConstants.getCurrentUser().getUserId());
		return "sysuser/getMyUser";
	}
	
	@LogAction(description="修改登录用户信息")
	@RequestMapping("/updateMyUser")
	public String updateMyUser(@ModelAttribute("sysUserFrom") SysUser sysUser, HttpSession session){
		ISessionMessageSetting sessionMessageSetting = GlobalConstants.setSessionMessage(session, "修改用户信息失败", "用户信息修改成功");
		try{
			if(StringUtils.isNotBlank(sysUser.getPassword())){
				sysUser.setPassword(MD5.toMD5(sysUser.getPassword()));
			}else{
				sysUser.setPassword(null);
			}
			sysUser.setModifier(GlobalConstants.getCurrentUser().getUserId());
			sysUser.setModifyTime(Calendar.getInstance().getTime());
			this.sysUserSerivce.updateSysUser(sysUser);
			sessionMessageSetting.setIsSuccess(true);
		}catch(Exception e){
			logger.error("修改用户信息", e);
		}
		return "redirect:/sysuser/getMyUser.do";
	}
	
	@RequestMapping("/getSysUser")
	public String getSysUser(Model model, @RequestParam String userId){
		SysUser sysUser = this.sysUserSerivce.getSysUserById(userId);
		model.addAttribute("sysUser", sysUser);
		return "sysuser/getSysUser";
	}
	
	@LogAction(description="修改用户信息")
	@RequestMapping("/updateSysUser")
	public String updateSysUser(@ModelAttribute("sysUserFrom") SysUser sysUser, HttpSession session){
		ISessionMessageSetting sessionMessageSetting = GlobalConstants.setSessionMessage(session, "修改用户信息失败", "用户信息修改成功");
		try{
			if(StringUtils.isNotBlank(sysUser.getPassword())){
				sysUser.setPassword(MD5.toMD5(sysUser.getPassword()));
			}
			sysUser.setModifier(GlobalConstants.getCurrentUser().getUserId());
			sysUser.setModifyTime(Calendar.getInstance().getTime());
			this.sysUserSerivce.updateSysUser(sysUser);
			sessionMessageSetting.setIsSuccess(true);
		}catch(Exception e){
			logger.error("修改用户信息", e);
		}
		return "redirect:/sysuser/querySysUserPage.do";
	}
	
	@RequestMapping("/querySysUserGroupPage")
	public String querySysUserGroupPage(Model model){
		SysUserGroup sysUserGroup = new SysUserGroup();
//		PageHelper.startPage(1, GlobalConstants.DEFAULT_PAGE_NUMBER);
		try{
			List<SysUserGroup> sysUserGroups = this.sysUserGroupService.getSysUserGroup(sysUserGroup);
			PageInfo<SysUserGroup> pageInfo = new PageInfo<SysUserGroup>(sysUserGroups);
			pageInfo.setList(sysUserGroups);
			model.addAttribute("pageInfo", pageInfo);
			model.addAttribute("flagProtect", GlobalConstants.FLAG_PROTECT);
		}catch(Exception e){
			logger.error("获取角色记录", e);
		}
		return "sysuser/querySysUserGroupPage";
	}
	
	@RequestMapping("/createSysUserGroup")
	public String createSysUserGroup(Model model){
		Map<String, String> flags = new HashMap<String, String>();
		flags.put(GlobalConstants.FLAG_ENABLE, "正常");
		flags.put(GlobalConstants.FLAG_PROTECT, "不可删除");
		model.addAttribute("flags", flags);
		return "sysuser/createSysUserGroup";
	}
	
	@RequestMapping("/saveSysUserGroup")
	@LogAction(description="创建角色")
	public String saveSysUserGroup(@ModelAttribute("sysUserGroupFrom") SysUserGroup sysUserGroup, HttpSession session){
		ISessionMessageSetting sessionMessageSetting = GlobalConstants.setSessionMessage(session, "创建角色失败", "创建角色成功");
		JsonReturnObject<String> jsonReturnObject = new JsonReturnObject<String>(false, "");
		sysUserGroup.setCreator(GlobalConstants.getCurrentUser().getUserId());
		try{
			this.sysUserGroupService.saveSysUserGroup(sysUserGroup);
			sessionMessageSetting.setIsSuccess(true);
		}catch(Exception e){
			logger.error("新建角色", e);
		}
		return "redirect:/sysuser/querySysUserGroupPage.do";
	}
	
	@RequestMapping("/updateSysUserGroup")
	@LogAction(description="修改用户组")
	public String updateSysUserGroup(@ModelAttribute("sysUserGroupFrom") SysUserGroup sysUserGroup, HttpSession session){
		ISessionMessageSetting sessionMessageSetting = GlobalConstants.setSessionMessage(session, "修改角色失败", "角色修改成功");
		try{
			sysUserGroup.setModifier(GlobalConstants.getCurrentUser().getUserId());
			sysUserGroup.setModifyTime(Calendar.getInstance().getTime());
			this.sysUserGroupService.updateSysUserGroup(sysUserGroup);
			sessionMessageSetting.setIsSuccess(true);
		}catch(Exception e){
			logger.error("修改用户组", e);
		}
		return "redirect:/sysuser/querySysUserGroupPage.do";
	}
	
	@LogAction(description="删除角色")
	@RequestMapping("/deleteSysUserGroup")
	@ResponseBody
	public JsonReturnObject<String> deleteSysUserGroup(@RequestParam String groupId, HttpSession session){
		JsonReturnObject<String> jsonReturnObject = new JsonReturnObject<String>(false, "删除角色失败");
		try{
			this.sysUserGroupService.deleteSysUserGroup(groupId);
			jsonReturnObject.setIsSuccess(true);
			jsonReturnObject.setReturnObject("删除角色成功");
		}catch(Exception e){
			logger.error("删除角色", e);
		}
		GlobalConstants.setSessionMessage(session, jsonReturnObject);
		return jsonReturnObject;
	}
	
	@RequestMapping("/getSysUserGroup")
	public String getSysUserGroup(Model model, @RequestParam String groupId){
		Map<String, String> flags = new HashMap<String, String>();
		flags.put(GlobalConstants.FLAG_ENABLE, "正常");
		flags.put(GlobalConstants.FLAG_PROTECT, "不可删除");
		model.addAttribute("flags", flags);
		SysUserGroup sysUserGroup = this.sysUserGroupService.getSysUserGroup(groupId);
		model.addAttribute("sysUserGroup", sysUserGroup);
		return "sysuser/getSysUserGroup";
	}
	
	@RequestMapping("/getSysUserGroups")
	@ResponseBody
	public JsonReturnObject<List<SysUserGroupVO>> getSysUserGroups(@RequestParam String userId){
		JsonReturnObject<List<SysUserGroupVO>> jsonReturnObject = new JsonReturnObject<List<SysUserGroupVO>>(false,"获取角色记录失败");
		try{
			SysUserGroup sysUserGroup = new SysUserGroup();
			List<SysUserGroup> sysUserGroups = this.sysUserGroupService.getSysUserGroup(sysUserGroup);
			SysUserGroupMebers sysUserGroupMebers = new SysUserGroupMebers();
			sysUserGroupMebers.setUserId(userId);
			List<SysUserGroupMebers> sysUserGroupMebersList = this.sysUserGroupMebersService.getSysUserGroupMebers(sysUserGroupMebers);
			List<SysUserGroupVO> sysUserGroupVOs = new ArrayList<SysUserGroupVO>();
			for(SysUserGroup temp : sysUserGroups){
				SysUserGroupVO sysUserGroupVO = new SysUserGroupVO();
				BeanUtils.copyProperties(sysUserGroupVO, temp);
				if(CollectionUtils.exists(sysUserGroupMebersList, new BeanPredicate("groupId", PredicateUtils.equalPredicate((temp.getGroupId()))))){
					sysUserGroupVO.setIsCheck(true);
				}else{
					sysUserGroupVO.setIsCheck(false);
				}
				sysUserGroupVOs.add(sysUserGroupVO);
			}
			jsonReturnObject.setIsSuccess(true);
			jsonReturnObject.setReturnObject(sysUserGroupVOs);
		}catch(Exception e){
			logger.error("获取角色记录", e);
		}
		return jsonReturnObject;
	}
	
	@RequestMapping("/saveSysUserGroupMebers")
	@LogAction(description="设置用户组")
	@ResponseBody
	public JsonReturnObject<String> saveSysUserGroupMebers(@RequestParam String userId, @RequestParam(name="groupId") String[] groupIds){
		JsonReturnObject<String> jsonReturnObject = new JsonReturnObject<String>(false, "设置角色失败");
		if(ArrayUtils.isNotEmpty(groupIds)){
			List<SysUserGroupMebers> sysUserGroupMebersList = new ArrayList<SysUserGroupMebers>();
			for(String groupId : groupIds){
				SysUserGroupMebers sysUserGroupMebers = new SysUserGroupMebers();
				sysUserGroupMebers.setGroupId(groupId);
				sysUserGroupMebers.setUserId(userId);
				sysUserGroupMebers.setAliveFlag(GlobalConstants.FLAG_ENABLE);
				sysUserGroupMebers.setCreator(GlobalConstants.SYSTEM_USER_ID);
				sysUserGroupMebersList.add(sysUserGroupMebers);
			}
			try{
				this.sysUserGroupMebersService.saveSysUserGroupMebersMany(sysUserGroupMebersList);
				jsonReturnObject.setIsSuccess(true);
				jsonReturnObject.setReturnObject("设置角色成功");
			}catch(Exception e){
				logger.error("设置角色", e);
			}
		}
		return jsonReturnObject;
	}
	
	@RequestMapping("/querySysMenuInfo")
	public String querySysMenuInfo(){
		return "sysuser/querySysMenuInfo";
	}
	
	@RequestMapping("/getSysMenuInfoTreeData")
	@ResponseBody
	public JsonReturnObject<Collection<SysMenuInfoVO>> getSysMenuInfoTreeData(@RequestParam(name="groupId",defaultValue="") String groupId){
		JsonReturnObject<Collection<SysMenuInfoVO>> jsonReturnObject = new JsonReturnObject<Collection<SysMenuInfoVO>>(false, "获取权限失败");
		try{
			SysMenuInfo sysMenuInfo = new SysMenuInfo();
			sysMenuInfo.setAliveFlag(GlobalConstants.FLAG_ENABLE);
			List<SysMenuInfo> sysMenuInfos = this.sysMenuInfoService.getSysMenuInfos(sysMenuInfo);
			List<SysUserGroupPower> sysUserGroupPowers = new ArrayList<SysUserGroupPower>();
			if(StringUtils.isNotBlank(groupId)){
				sysUserGroupPowers = this.sysUserGroupPowerService.getSysUserGroupPowersByRoleId(groupId);
			}
			
			Comparator<Long> comparator = ComparableComparator.getInstance();
			comparator = ComparatorUtils.nullHighComparator(comparator);
			ComparatorChain comparatorChain = new ComparatorChain(new BeanComparator<Long>("orderBy", comparator));
			comparatorChain.addComparator(new BeanComparator<String>("menuId"));
			SortedSet<SysMenuInfoVO> sysMenuInfoVOs = new TreeSet<SysMenuInfoVO>(comparatorChain);
			for(SysMenuInfo tmp : sysMenuInfos){
				SysMenuInfoVO sysMenuInfoVO = new SysMenuInfoVO();
				BeanUtils.copyProperties(sysMenuInfoVO, tmp);
				sysMenuInfoVO.setOpen(true);
				if(CollectionUtils.exists(sysUserGroupPowers, new BeanPredicate("menuId", PredicateUtils.equalPredicate(sysMenuInfoVO.getMenuId())))){
					sysMenuInfoVO.setChecked(true);
				}
				sysMenuInfoVOs.add(sysMenuInfoVO);
			}
			jsonReturnObject.setIsSuccess(true);
			SysMenuInfoVO sysMenuInfoVO = new SysMenuInfoVO();
			sysMenuInfoVO.setMenuId("0");
			sysMenuInfoVO.setMenuName("MEOA系统");
			sysMenuInfoVO.setOpen(true);
			sysMenuInfoVOs.add(sysMenuInfoVO);
			jsonReturnObject.setReturnObject(sysMenuInfoVOs);
		}catch(Exception e){
			logger.error("获取权限", e);
		}
		return jsonReturnObject;
	}
	
	@RequestMapping("/getSysMenuInfoData")
	@ResponseBody
	public JsonReturnObject<SysMenuInfo> getSysMenuInfoData(@RequestParam String menuId){
		JsonReturnObject<SysMenuInfo> jsonReturnObject = new JsonReturnObject<SysMenuInfo>(false, "获取权限失败");
		try {
			SysMenuInfo sysMenuInfo = this.sysMenuInfoService.getSysMenuInfo(menuId);
			jsonReturnObject.setIsSuccess(true);
			jsonReturnObject.setReturnObject(sysMenuInfo);
		} catch (Exception e) {
			logger.error("获取权限", e);
		}
		return jsonReturnObject;
	}
	
	@LogAction(description="新增权限")
	@RequestMapping("/saveSysMenuInfo")
	@ResponseBody
	public JsonReturnObject<String> saveSysMenuInfo(@ModelAttribute("menuForm") SysMenuInfo sysMenuInfo){
		JsonReturnObject<String> jsonReturnObject = new JsonReturnObject<String>(false, "保存权限失败");
		sysMenuInfo.setAliveFlag(GlobalConstants.FLAG_ENABLE);
		sysMenuInfo.setCreator(GlobalConstants.getCurrentUser().getUserId());
		try {
			this.sysMenuInfoService.saveSysMenuInfo(sysMenuInfo);
			jsonReturnObject.setIsSuccess(true);
			jsonReturnObject.setReturnObject("保存成功");
		} catch (Exception e) {
			logger.error("保存权限", e);
		}
		return jsonReturnObject;
	}
	
	@LogAction(description="修改权限")
	@RequestMapping("/updateSysMenuInfo")
	@ResponseBody
	public JsonReturnObject<String> updateSysMenuInfo(@ModelAttribute("menuForm") SysMenuInfo sysMenuInfo){
		JsonReturnObject<String> jsonReturnObject = new JsonReturnObject<String>(false, "修改权限失败");
		sysMenuInfo.setModifier(GlobalConstants.getCurrentUser().getUserId());
		try {
			this.sysMenuInfoService.updateSysMenuInfo(sysMenuInfo);
			jsonReturnObject.setIsSuccess(true);
			jsonReturnObject.setReturnObject("修改成功");
		} catch (Exception e) {
			logger.error("修改权限", e);
		}
		return jsonReturnObject;
	}
	
	@LogAction(description="设置用户组权限")
	@RequestMapping("/saveSysGroupMenuInfo")
	@ResponseBody
	public JsonReturnObject<String> saveSysGroupMenuInfo(@RequestParam("groupId") String groupId,@RequestParam("menuIds") String menuIds){
		JsonReturnObject<String> jsonReturnObject = new JsonReturnObject<String>(false, "保存权限失败");
		if(StringUtils.isNotBlank(groupId) && StringUtils.isNotBlank(menuIds)){
			try {
				List<String> menuIdList = new ArrayList<String>(Arrays.asList(menuIds.split(",")));
//				移除系统标识
				menuIdList.remove("0");
				this.sysUserGroupPowerService.saveSysUserGroupPowers(groupId, menuIdList);
				jsonReturnObject.setIsSuccess(true);
				jsonReturnObject.setReturnObject("设置用户组权限成功");
			} catch (Exception e) {
				logger.error("设置用户组权限", e);
			}
		}
		return jsonReturnObject;
	}
	
	@RequestMapping("/querySysUserByGroup")
	public String querySysUserByGroup(@RequestParam String groupId, Model model){
		model.addAttribute("groupId", groupId);
		return "sysuser/querySysUserByGroup";
	}
	
	@RequestMapping("/getSysUserByGroup")
	@ResponseBody
	public JsonReturnObject<DatatablesJson<SysUserGroupMebers>> getSysUserByGroup(@RequestParam String groupId, @RequestParam String sEcho, @RequestParam int iDisplayStart,@RequestParam int iDisplayLength,@RequestParam(required=false) String sSearch){
		JsonReturnObject<DatatablesJson<SysUserGroupMebers>> jsonReturnObject = new JsonReturnObject<DatatablesJson<SysUserGroupMebers>>(false,"获取用户组成员失败");
		PageHelper.startPage((iDisplayStart/iDisplayLength)+1, iDisplayLength);
		try {
			SysUserGroupMebers sysUserGroupMebers = new SysUserGroupMebers();
			sysUserGroupMebers.setGroupId(groupId);
			sysUserGroupMebers.setAliveFlag(GlobalConstants.FLAG_ENABLE);
			if(StringUtils.isNotBlank(sSearch)){
				SysUser sysUser = new SysUser();
				sysUser.setUserName(sSearch);
				sysUserGroupMebers.setSysUser(sysUser);
			}
			List<SysUserGroupMebers> sysUserGroupMebersList = this.sysUserGroupMebersService.getSysUserGroupMebersByGroup(sysUserGroupMebers);
			DatatablesJson<SysUserGroupMebers> datatablesJson = new DatatablesJson<SysUserGroupMebers>();
			datatablesJson.setEcho(sEcho);
			PageInfo<SysUserGroupMebers> pageInfo = new PageInfo<SysUserGroupMebers>(sysUserGroupMebersList);
			datatablesJson.setTotalRecords(Long.valueOf(pageInfo.getTotal()).intValue());
			datatablesJson.setTotalDisplayRecords(Long.valueOf(pageInfo.getTotal()).intValue());
			datatablesJson.setData(pageInfo.getList());
			jsonReturnObject.setIsSuccess(true);
			jsonReturnObject.setReturnObject(datatablesJson);
		} catch (Exception e) {
			logger.error("获取用户组成员", e);
		}
		return jsonReturnObject;
	}
	
	@RequestMapping("/updateLeader")
	@ResponseBody
	@LogAction(description="设置用户组负责人")
	public JsonReturnObject<String> updateLeader(String groupId, String userId){
		JsonReturnObject<String> jsonReturnObject = new JsonReturnObject<String>(false,"设置负责人失败");
		SysUserGroupMebers sysUserGroupMebers = new SysUserGroupMebers();
		sysUserGroupMebers.setGroupId(groupId);
		sysUserGroupMebers.setUserId(userId);
		sysUserGroupMebers.setIsLeader(GlobalConstants.FLAG_ENABLE);
		try{
			this.sysUserGroupMebersService.updateLeader(sysUserGroupMebers);
			jsonReturnObject.setIsSuccess(true);
			jsonReturnObject.setReturnObject("成功设置负责人");
		}catch(Exception e){
			logger.error("设置负责人", e);
		}
		return jsonReturnObject;
	}
}
